package com.lear.njava.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lear.njava.pojo.Admin;
import com.lear.njava.service.AdminService;
import com.lear.njava.util.MD5;
import com.lear.njava.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController // 异步交互方法
@RequestMapping("/sms/adminController") // 请求映射路径
public class AdminController {

    @Autowired // 注入AdminService
    private AdminService adminService;

    // GET /sms/adminController/getAllAdmin/1/3?adminName=xxx
    @GetMapping("/getAllAdmin/{pageNo}/{pageSize}")
    public Result getAllAdmin(
            @PathVariable("pageNo") Integer pageNo,
            @PathVariable("pageSize") Integer pageSize,
            String adminName
    ){
        // 1.获取参数 2.调用服务层 3.返回结果
        // Page对象封装分页信息
        Page<Admin> pageParam = new Page<Admin>(pageNo, pageSize);
        // 调用服务层
        IPage<Admin> iPage = adminService.getAdminsByOpr(pageParam, adminName);
        return Result.ok(iPage);
    }

    // POST /sms/adminController/saveOrUpdateAdmin admin
    @PostMapping("/saveOrUpdateAdmin")
    public Result saveOrUpdateAdmin(
            @RequestBody Admin admin // 将参数赋给Admin对象
    ){
        // 判断是新增管理员还是修改，有无id
        Integer id = admin.getId();
        if (null == id || 0 == id) {
            // 对密码进行加密
            String password = admin.getPassword();
            admin.setPassword(MD5.encrypt(password));
        }
        adminService.saveOrUpdate(admin);
        return Result.ok();
    }

    // DELETE /sms/adminController/deleteAdmin List<Integer> ids
    @DeleteMapping("/deleteAdmin")
    public Result deleteAdmin(
            @RequestBody List<Integer> ids
            ){
        adminService.removeByIds(ids);
        return Result.ok();
    }
}
